// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;

namespace SnapObjects.Commons
{
    public static class Extensions
    {
        public static bool IsNullable(this Type type)
        {
            return Nullable.GetUnderlyingType(type) != null;
        }

        public static bool CanAssignedNull(this Type type)
        {
            return !type.IsValueType
                || (type.IsValueType && type.IsNullable());
        }

        public static bool IsModel(this Type type)
        {
            return !type.IsValueType
                && type.IsClass
                && type != typeof(string);
        }

        public static object DefaultValue(this Type type)
        {
            if (type == null || type.CanAssignedNull())
            {
                return null;
            }

            var code = Type.GetTypeCode(type);

            switch (code)
            {
                case TypeCode.Boolean: return false;
                case TypeCode.Byte: return default(byte);
                case TypeCode.Char: return default(char);
                case TypeCode.SByte: return default(sbyte);

                case TypeCode.UInt16: return default(ushort);
                case TypeCode.UInt32: return default(uint);
                case TypeCode.UInt64: return default(ulong);

                case TypeCode.Int16: return default(short);
                case TypeCode.Int32: return default(int);
                case TypeCode.Int64: return default(long);

                case TypeCode.Single: return default(float);
                case TypeCode.Double: return default(double);
                case TypeCode.Decimal: return default(decimal);
                case TypeCode.DateTime: return default(DateTime);
            }

            return Activator.CreateInstance(type);
        }
    }
}
